package com.axsoft.train;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * This class implements some Http-related routines
 * 
 */
class HttpUtils {
	
	
	/**
	 * Make http GET request
	 */
	public static String getRequest(final String url)	{
		if ( url == null ) {
			return null; // DO NOT return null
		}
		
		String html = null;
		HttpClient httpClient = null;
		HttpGet httpGet = null;
		ResponseHandler<String> responseHandler = null;
		
		try	{
			httpClient = new DefaultHttpClient();
			httpGet = new HttpGet(url);
			
			responseHandler = new ResponseHandler<String>() {
				@Override
				public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
					final StatusLine statusLine = response.getStatusLine();
					
					if (statusLine.getStatusCode() >= 300) {
						throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
					}
					
					final HttpEntity entity = response.getEntity();
					return ((entity == null) ? null : EntityUtils.toString(entity, "UTF-8")); // FIXME: Do NOT return NULL
				}
			};
			
			html = httpClient.execute(httpGet, responseHandler);
			httpClient.getConnectionManager().shutdown();
		} catch (Exception e)	{
			Log.e("HttpUtils.getRequest", e.toString());
			return null; // DO NOT return Null
		}
		
		return html;		
	}
	
	
	/**
	 * Gets train list for the given directions
	 */
	public static List<Train> getSchedule(final String from, final String to, final boolean nearest) {
		if (from == null || to == null) {
			return null; // TODO: We should not return null
		}
		
		String url = Constants.URL_SUBURBAN_SEARCH + "station_from=" + from +
					 "&station_to" + to;
		if (!nearest) {
			url += "&mode=all";
		}
		
		String html = getRequest(url);
		
		if (html == null) {
			return null; // FIXME: Don NOT return null!
		}
		
		final int startIndex = html.indexOf("train\">");
		if (startIndex == -1) {
			return null;
		}
		
		html = html.substring(startIndex);
		if (html == null) {
			return null;
		}
		
		final List<Train> trains = new ArrayList<Train>();
		
		Train train = null;
		
		do {
			train = new Train();
			train.fromString(html, nearest);
			
			if (train.isValid) {
				trains.add(train);
			}
			
		} while (train != null && train.isValid);
		
		return trains;
	}
	
	
	/**
	 * Opens file for read
	 */
	public static BufferedReader openFileForRead(final String fileName) {
		try {
			FileInputStream is = new FileInputStream(fileName);
			return new BufferedReader(new InputStreamReader(is, "utf8"), 8192);
		} catch (Exception e) {
			Log.e("HttpUtils.openFileForRead", e.toString());
			return null;
		}
	}
	
}